//條棒滾到heading的位置。
//需要提供 1. {$title} =目標名稱 2. {$index} =出現次數索引

function getElementsByTagNames(list,obj) {
    if (!obj) var obj = document;
        var tagNames = list.split(',');
    var resultArray = new Array();
    for (var i=0;i<tagNames.length;i++) {
        var tags = obj.getElementsByTagName(tagNames[i]);
        for (var j=0;j<tags.length;j++) {
            resultArray.push(tags[j]);
        }
    }
    var testNode = resultArray[0];
    if (!testNode) return [];
    if (testNode.sourceIndex) {
        resultArray.sort(function (a,b) {
            return a.sourceIndex - b.sourceIndex;
        });
    }
    else if (testNode.compareDocumentPosition) {
        resultArray.sort(function (a,b) {
            return 3 - (a.compareDocumentPosition(b) & 6);
        });
    }
    return resultArray;
}

function findPosY(obj) {
    var curtop = 0;
    while(obj.offsetParent) {
        curtop += obj.offsetTop;
        obj = obj.offsetParent;
        }
    return curtop;
}

function scrollToAnimation(targetPos, dur) {
    var startTime = (new Date).getTime();
    var endTime = startTime + dur;
    var pageYOffset = window.pageYOffset;
    var needToMove = targetPos - pageYOffset;
    var currentTime = (new Date).getTime();
    stepMove = function() {
        currentTime = (new Date).getTime();
        stepTarget = (((currentTime - startTime) / dur) * needToMove) + pageYOffset;
        window.scrollTo(0,stepTarget)
        }
    id = window.setInterval(stepMove,10);
    window.setTimeout(window.clearInterval, dur, id);
    return window.setTimeout(window.scrollTo, dur, 0, targetPos);
}

scrollToHeading = function(anchorName ,index) {
    if (!index){
        index = 0;
    }

    var children = getElementsByTagNames("h1,h2,h3,h4,h5,h6");

    for (var i = 0; i < children.length; i++) {
        var heading = children[i].innerHTML;

        // Remove all HTML tags
        while (heading.indexOf("<") >= 0) {
            heading = heading.substring(0, heading.indexOf("<")) + heading.substring(heading.indexOf(">") + 1);
        }

        if (heading == anchorName) {
            if (index == 0) {
                var y = findPosY(children[i]);
                return scrollToAnimation(y, 200)
                //window.scrollTo(0,y);
                return true;
            }
            else {
                --index;
            }
        }
    }
    return false;
};
scrollToHeading("{$title}", {$index});
